import { getUserInfo, login } from '@/api/user'
import { getToken, getUserId, removeToken, removeUserId, setToken, setUserId } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userId: getUserId(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserId(state, id) {
      state.userId = id
      setUserId(id)
    },
    removeUserId(state) {
      state.userId = null
      removeUserId()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      context.commit('setUserId', res.userId)
      context.commit('setToken', res.token)
    },
    async getUserInfo(context) {
      const res = await getUserInfo(context.state.userId)
      context.commit('setUserInfo', res)
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserId')
      context.commit('setUserInfo', {})
    }
  }
}
